package com.csc775.networking;


import java.net.*;
import java.io.*;

import com.csc775.gui.AndroidClient;
import com.csc775.message.ControlMessage;

public class Client
{  private Socket TCPsocket = null;
   private DataInputStream  console   = null;
   private DataOutputStream streamOut = null;
   private DataInputStream  in   = null;
   private DataOutputStream out = null;
   private ObjectInputStream  Sin   = null;
   private ObjectOutputStream Sout = null;
   private DatagramSocket UDPsocket;
   private int port;
   private int group = 0;
   String hostname;

   public Client() 
   {  
     
      /*String line = "";
      while (!line.equals(".bye"))
      {  try
         { 
    	  line = console.readLine();
    	  streamOut.writeUTF(line);
            streamOut.flush();
         }
         catch(IOException ioe)
         {  System.out.println("Sending error: " + ioe.getMessage());
         }
      }*/
   }
   
   public void run(){
	   try{
		      InetAddress addr = InetAddress.getLocalHost();
				byte[] ipAddr = addr.getAddress();
				hostname = addr.getHostName();
		      TCPsocket = new Socket("192.168.2.4", 2004);
		      UDPsocket = new DatagramSocket();
		      connectMessage();
		         //System.out.println("Connected: " + TCPsocket);
		      //   start();
		         }
		      catch(UnknownHostException uhe)
		      {  System.out.println("Host unknown: " + uhe.getMessage());
		      }
		      catch(IOException ioe)
		      {  System.out.println("Unexpected exception: " + ioe.getMessage());
		      }
   }
   
   public void connectMessage(){
	   ControlMessage msg = new ControlMessage("192.168.2.4", 2004, 1, null);
	   Sendmessage(String.valueOf(msg));
   }
   
   public void start(){
	   try{
		   console   = new DataInputStream(System.in);
		   streamOut = new DataOutputStream(TCPsocket.getOutputStream());
	     Sout = new ObjectOutputStream(TCPsocket.getOutputStream());
		Sout.flush();
		Sin = new ObjectInputStream(TCPsocket.getInputStream());
		recevMsg();
    	Sendmessage(String.valueOf(selectGroup()));
		
		BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
		       byte[] sendData = new byte[1024];
		      byte[] receiveData = new byte[1024];
		      
		      String sentence = inFromUser.readLine();
		      sendData = sentence.getBytes();
		DatagramPacket sendPacket = buildPacket (sentence, hostname, TCPsocket.getLocalPort());
	     UDPsocket.send(sendPacket);
	      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
	      UDPsocket.receive(receivePacket);
	      String modifiedSentence = new String(receivePacket.getData());
	      System.out.println("FROM SERVER:" + modifiedSentence);
	   }catch (Exception e){
		   System.out.println(e);
	   }
	   
   }
   
   public void recevMsg(){
	   try{
			String message = (new ObjectInputStream(TCPsocket.getInputStream())).readObject().toString();
			System.out.println("from server>" + message);
	   }catch (Exception e){
	   System.out.println(e);
  }   
   }
   
   public void Sendmessage(String msg){
			try{
				msg="hi";
//BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
	//String message = inFromUser.readLine();
Sout.writeObject(msg);
Sout.flush();
		//		System.out.println("Sent(client):" + msg);
		
			
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
   
   /**
    * User selects group
    * @return
    */
   public int selectGroup(){
	   
	   return group++;
   }
   
   public void stop()
   {  try
      {  if (console   != null)  console.close();
         if (streamOut != null)  streamOut.close();
         if (TCPsocket    != null)  TCPsocket.close();
         if (UDPsocket    != null)  UDPsocket.close();
         if (Sout    != null)  Sout.close();
         if (Sin    != null)  Sin.close();
      }
      catch(IOException ioe)
      {  System.out.println("Error closing ...");
      }
   }
   
   public DatagramPacket buildPacket (String message, String host, int port) throws IOException {

	// Create a byte array from a string
	ByteArrayOutputStream byteOut = new ByteArrayOutputStream ();
	DataOutputStream dataOut = new DataOutputStream (byteOut);
	dataOut.writeBytes(message);
	byte[] data = byteOut.toByteArray ();
	//Return the new object with the byte array payload
	return new DatagramPacket (data, data.length, InetAddress.getByName(host), port);
	}
   
   
  /* public static void main(String args[]) throws ClassNotFoundException
   {  
	       Client client = new Client("ruhi", 2004);
   }*/
}
